#include "PresetPositionManager.h"

#include <QCheckBox>
#include <QLabel>

#include "../Device_Motor/Device_Motor.h"
#include <QTimer>
#include <QMessageBox>

PresetPositionManager::PresetPositionManager(std::shared_ptr<Device_Motor> motor, QWidget *parent)
    : QWidget(parent), m_motor(motor)
{
    setupUI();

}

PresetPositionManager::~PresetPositionManager()
{
}
void PresetPositionManager::setupUI()
{
    // 初始化 UI 组件
    m_presetPositionSpinBox = new QDoubleSpinBox(this);
    m_presetPositionSpinBox->setRange(0, 999);
    m_presetNameEdit = new QLineEdit(this);
    m_presetListView = new QListWidget(this);
    m_moveUpButton = new QPushButton(QString::fromUtf8("↑") + " 上移", this);
    m_moveDownButton = new QPushButton(QString::fromUtf8("↓") + " 下移", this);
    m_sequentialMoveButton = new QPushButton(QString::fromUtf8("⇄") + " 顺序移动", this);
    m_addButton = new QPushButton(QString::fromUtf8("+") + " 添加", this);
    m_removeButton = new QPushButton(QString::fromUtf8("×") + " 删除", this);
    m_clearButton = new QPushButton(QString::fromUtf8("⌧") + " 清空", this);
    m_loadButton = new QPushButton(QString::fromUtf8("📂") + " 加载", this);
    m_saveButton = new QPushButton(QString::fromUtf8("💾") + " 保存", this);
    m_moveToButton = new QPushButton(QString::fromUtf8("→") + " 移动到", this);
    m_isMeasurementCheckBox = new QCheckBox("测量模式", this);
    m_isMeasurementCheckBox->setChecked(false);

    // 布局设置 - 重新设计为更合理的布局
    QVBoxLayout *mainLayout = new QVBoxLayout(this);

    // 输入区域 - 顶部
    QHBoxLayout *inputLayout = new QHBoxLayout();

    // 输入控件
    QLabel *positionLabel = new QLabel("位置:", this);
    QLabel *nameLabel = new QLabel("名称:", this);


    inputLayout->addWidget(positionLabel);
    inputLayout->addWidget(m_presetPositionSpinBox);
    inputLayout->addWidget(nameLabel);
    inputLayout->addWidget(m_presetNameEdit);
    inputLayout->addWidget(m_addButton);
    inputLayout->addWidget(m_removeButton);
    inputLayout->addWidget(m_moveToButton);


    QHBoxLayout *controlLayout = new QHBoxLayout();

    QHBoxLayout *moveButtons = new QHBoxLayout();
    moveButtons->addWidget(m_moveUpButton);
    moveButtons->addWidget(m_moveDownButton);
    moveButtons->addWidget(m_sequentialMoveButton);
    moveButtons->addWidget(m_isMeasurementCheckBox);

    QHBoxLayout *fileButtons = new QHBoxLayout();
    fileButtons->addWidget(m_clearButton);
    fileButtons->addWidget(m_loadButton);
    fileButtons->addWidget(m_saveButton);

    controlLayout->addLayout(moveButtons);
    controlLayout->addLayout(fileButtons);

    mainLayout->setSpacing(10);
    mainLayout->setContentsMargins(10, 10, 10, 10);
    inputLayout->setSpacing(5);
    controlLayout->setSpacing(5);
    moveButtons->setSpacing(5);
    fileButtons->setSpacing(5);

    // 添加到主布局
    mainLayout->addLayout(inputLayout);
    mainLayout->addWidget(m_presetListView, 1);
    mainLayout->addLayout(controlLayout);

    // 信号槽连接
    connect(m_addButton, &QPushButton::clicked, this, &PresetPositionManager::onAddPresetClicked);
    connect(m_removeButton, &QPushButton::clicked, this, &PresetPositionManager::onRemovePresetClicked);
    connect(m_moveToButton, &QPushButton::clicked, this, &PresetPositionManager::onMoveToPresetClicked);
    connect(m_moveUpButton, &QPushButton::clicked, this, &PresetPositionManager::onMoveUpPresetClicked);
    connect(m_moveDownButton, &QPushButton::clicked, this, &PresetPositionManager::onMoveDownPresetClicked);
    connect(m_sequentialMoveButton, &QPushButton::clicked, this, &PresetPositionManager::onSequentialMoveClicked);
    connect(m_isMeasurementCheckBox, &QCheckBox::stateChanged, this, [this](int state) {
       bool checked =m_isMeasurementCheckBox->isChecked();
        m_isMeasurement = checked;
    });
    connect(m_clearButton, &QPushButton::clicked, this, &PresetPositionManager::onClearPresetsClicked);
    connect(m_loadButton, &QPushButton::clicked, this, &PresetPositionManager::onLoadFromFileClicked);
    connect(m_saveButton, &QPushButton::clicked, this, &PresetPositionManager::onSaveToFileClicked);
    connect(m_presetListView, &QListWidget::itemDoubleClicked, this, &PresetPositionManager::onPresetDoubleClicked);
}

void PresetPositionManager::moveAllPresetsSequentially(bool m_isMeasurement)
{
    if (m_presetPositions.isEmpty()) {
        QMessageBox::information(this, "提示", "预设位置列表为空");
        return;
    }

    m_isSequentialMoving = true;
    m_currentPresetIndex = 0;

    // 使用QTimer逐个移动所有预设位置
    QTimer *timer = new QTimer(this);
    connect(timer, &QTimer::timeout, this, [this, timer, m_isMeasurement]() {
        if (m_currentPresetIndex >= m_presetPositions.size()) {
            timer->stop();
            timer->deleteLater();
            m_isSequentialMoving = false;
            QMessageBox::information(this, "完成", "所有移动完成");
            return;
        }

        const auto &preset = m_presetPositions[m_currentPresetIndex];
        emit requestMoveToPreset(preset.position,m_isMeasurement);
        m_currentPresetIndex++;
    });

    timer->start(1000); // 每秒移动一个位置
}

void PresetPositionManager::moveToPreset(int index)
{
    if (index < 0 || index >= m_presetPositions.size()) {
        QMessageBox::warning(this, "警告", "无效的预设位置索引");
        return;
    }

    const auto &preset = m_presetPositions[index];
    emit requestMoveToPreset(preset.position,m_isMeasurement);
}

void PresetPositionManager::loadFromFile(const QString &path)
{
    QFile file(path);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        QMessageBox::warning(this, "错误", "无法打开文件: " + path);
        return;
    }

    QList<PresetPosition> loadedPresets;
    QTextStream in(&file);
    int presetCount = 0;

    while (!in.atEnd()) {
        QString line = in.readLine().trimmed();
        if (line.isEmpty()) continue;

        QStringList parts = line.split(',');
        
        // 处理两种格式：1. 名称,位置  2. 只有位置
        if (parts.size() >= 2) {
            // 格式：名称,位置
            QString name = parts[0].trimmed();
            bool ok;
            double position = parts[1].toDouble(&ok);

            if (ok) {
                // 如果名称为空，自动生成名称（使用位置数据）
                if (name.isEmpty()) {
                    name = QString("位置_%1").arg(position);
                }
                loadedPresets.append(PresetPosition(name, position, Qt::white, presetCount));
                presetCount++;
            }
        } else if (parts.size() == 1) {
            // 格式：只有位置
            bool ok;
            double position = parts[0].toDouble(&ok);
            
            if (ok) {
                QString name = QString("位置_%1").arg(position);
                loadedPresets.append(PresetPosition(name, position, Qt::white, presetCount));
                presetCount++;
            }
        }
    }

    file.close();

    if (!loadedPresets.isEmpty()) {
        m_presetPositions = loadedPresets;
        
        // 直接操作列表视图更新显示
        m_presetListView->clear();
        for (int i = 0; i < m_presetPositions.size(); ++i) {
            const auto &preset = m_presetPositions[i];
            QString itemText = QString("%1: %2").arg(preset.name).arg(preset.position);
            QListWidgetItem *item = new QListWidgetItem(itemText, m_presetListView);
            item->setData(Qt::UserRole, i);
            m_presetListView->addItem(item);
        }
        
        QMessageBox *msgBox = new QMessageBox(this);
    msgBox->setWindowTitle("成功");
    msgBox->setText(QString("成功加载 %1 个预设位置").arg(loadedPresets.size()));
    msgBox->setAttribute(Qt::WA_DeleteOnClose); // 自动销毁
    msgBox->setModal(false); // 非模态，不阻塞
    msgBox->show();

    // 3秒后自动关闭
    QTimer::singleShot(3000, msgBox, &QMessageBox::close);
    } else {
        QMessageBox::warning(this, "警告", "文件中没有有效的预设位置数据");
    }
}

void PresetPositionManager::saveToFile(const QString &path)
{
    if (m_presetPositions.isEmpty()) {
        QMessageBox::warning(this, "警告", "预设位置列表为空，无法保存");
        return;
    }

    QFile file(path);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        QMessageBox::warning(this, "错误", "无法创建文件: " + path);
        return;
    }

    QTextStream out(&file);

    for (const auto &preset : m_presetPositions) {
        out << preset.name << "," << preset.position << "\n";
    }

    file.close();
    QMessageBox::information(this, "成功", QString("成功保存 %1 个预设位置").arg(m_presetPositions.size()));
}

void PresetPositionManager::addPreset(const QString &name, double position)
{

    for (const auto &preset : m_presetPositions) {
        if (preset.name == name) {
            QMessageBox::warning(this, "警告", "已存在同名预设位置");
            return;
        }
    }
    QString finalName = name.isEmpty() ?
        "位置" + QString::number(m_presetPositions.size() + 1) :
        name;
    PresetPosition newPreset(finalName, position, Qt::white, m_presetPositions.size());
    m_presetPositions.append(newPreset);
    QString itemText = QString("%1: %2").arg(finalName).arg(position);
    QListWidgetItem *item = new QListWidgetItem(itemText, m_presetListView);
    item->setData(Qt::UserRole, newPreset.index);
    m_presetListView->addItem(item);
}

void PresetPositionManager::onAddPresetClicked()
{
    QString name = m_presetNameEdit->text();
    double position = m_presetPositionSpinBox->value();
    addPreset(name, position);
}

void PresetPositionManager::removePreset(int index)
{
    if (index < 0 || index >= m_presetPositions.size()) {
        QMessageBox::warning(this, "警告", "无效的预设位置索引");
        return;
    }
    m_presetPositions.removeAt(index);
    for (int i = index; i < m_presetPositions.size(); i++) {
        m_presetPositions[i].index = i;
    }

    delete m_presetListView->takeItem(index);

    for (int i = index; i < m_presetListView->count(); i++) {
        m_presetListView->item(i)->setData(Qt::UserRole, i);
    }

}

void PresetPositionManager::onRemovePresetClicked()
{
    QListWidgetItem *currentItem = m_presetListView->currentItem();
    if (!currentItem) {
        QMessageBox::warning(this, "警告", "请先选择一个预设位置");
        return;
    }

    int index = currentItem->data(Qt::UserRole).toInt();
    removePreset(index);
}

void PresetPositionManager::onMoveToPresetClicked()
{
    QListWidgetItem *currentItem = m_presetListView->currentItem();
    if (!currentItem) {
        QMessageBox::warning(this, "警告", "请先选择一个预设位置");
        return;
    }

    int index = currentItem->data(Qt::UserRole).toInt();
    moveToPreset(index);
}


void PresetPositionManager::clearPresets()
{
    if (m_presetPositions.isEmpty()) {
     //   QMessageBox::information(this, "提示", "预设位置列表已为空");
        return;
    }

    int ret = QMessageBox::question(this, "确认", "确定要清空所有预设位置吗？",
                                  QMessageBox::Yes | QMessageBox::No);

    if (ret == QMessageBox::Yes) {
        m_presetPositions.clear();
        m_presetListView->repaint();
    }
}

void PresetPositionManager::onClearPresetsClicked()
{
    clearPresets();
}

void PresetPositionManager::onLoadFromFileClicked()
{
    QString path = QFileDialog::getOpenFileName(this, "选择预设位置文件", "", "文本文件 (*.txt);;所有文件 (*)");
    if (!path.isEmpty()) {
        loadFromFile(path);
    }
}

void PresetPositionManager::onSaveToFileClicked()
{
    QString path = QFileDialog::getSaveFileName(this, "保存预设位置文件", "", "文本文件 (*.txt);;所有文件 (*)");
    if (!path.isEmpty()) {
        saveToFile(path);
    }
}

void PresetPositionManager::onPresetDoubleClicked(QListWidgetItem *item)
{
    int index = item->data(Qt::UserRole).toInt();
    if (index >= 0 && index < m_presetPositions.size()) {
        const auto &preset = m_presetPositions[index];
        m_presetNameEdit->setText(preset.name);
        m_presetPositionSpinBox->setValue(preset.position);
    }
}


void PresetPositionManager::onMoveUpPresetClicked()
{
    QListWidgetItem *currentItem = m_presetListView->currentItem();
    if (!currentItem) {
        QMessageBox::warning(this, "警告", "请先选择一个预设位置");
        return;
    }

    int index = currentItem->data(Qt::UserRole).toInt();
    if (index > 0) {

        m_presetPositions.swapItemsAt(index, index - 1);

        QListWidgetItem* upperItem = m_presetListView->item(index - 1);
        QString currentText = currentItem->text();
        QString upperText = upperItem->text();
        currentItem->setText(upperText);
        upperItem->setText(currentText);

        currentItem->setData(Qt::UserRole, index - 1);
        upperItem->setData(Qt::UserRole, index);

        m_presetListView->setCurrentRow(index - 1);

    }
}

void PresetPositionManager::onMoveDownPresetClicked()
{
    QListWidgetItem *currentItem = m_presetListView->currentItem();
    if (!currentItem) {
        QMessageBox::warning(this, "警告", "请先选择一个预设位置");
        return;
    }

    int index = currentItem->data(Qt::UserRole).toInt();
    if (index < m_presetPositions.size() - 1) {

        m_presetPositions.swapItemsAt(index, index + 1);

        QListWidgetItem* lowerItem = m_presetListView->item(index + 1);
        QString currentText = currentItem->text();
        QString lowerText = lowerItem->text();
        currentItem->setText(lowerText);
        lowerItem->setText(currentText);

        currentItem->setData(Qt::UserRole, index + 1);
        lowerItem->setData(Qt::UserRole, index);

        m_presetListView->setCurrentRow(index + 1);

    }
}

void PresetPositionManager::onSequentialMoveClicked()
{
    moveAllPresetsSequentially(m_isMeasurement);
}
